/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * <p>
 * MpmProjectMilepostService 项目策划-里程碑及任务
 * <p>
 * 修改纪录 2021-01-06 版本：1.0 wudaliang 创建。
 *
 * @version 版本：1.0
 * @author 作者：wudaliang 创建日期：2021-01-06
 */
package com.topscomm.mpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.BasicSystemConst;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.utils.MessageUtil;
import com.topscomm.pub.util.*;
import cn.hutool.core.date.DateUtil;
import com.topscomm.pub.vo.ResponseResult;

import java.io.File;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectMilepostService;
import com.topscomm.mpm.service.impl.auto.MpmProjectMilepostServiceAuto;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Service(value = "mpmProjectMilepostService")
@Scope(value = "singleton")
public class MpmProjectMilepostService extends MpmProjectMilepostServiceAuto implements
        IMpmProjectMilepostService {

    @Autowired
    private MpmProjectPlanService mpmProjectPlanService;

    @Autowired
    private MpmProjectTaskService mpmProjectTaskService;

    @Autowired
    private MpmMilePostTemplateService mpmMilePostTemplateService;

    @Autowired
    private MpmProjectService mpmProjectService;
    @Autowired
    private MpmProjectTaskTemplateService mpmProjectTaskTemplateService;
    @Autowired
    private MpmCustomerAnalysisService mpmCustomerAnalysisService;
    @Autowired
    private MpmProjectCompetitorService mpmProjectCompetitorService;
    @Autowired
    private MpmProjectSuperviseService mpmProjectSuperviseService;
    @Autowired
    private DatacodeCache datacodeCache;
    @Autowired
    private ICboMessageAppService cboMessageAppService;
    @Autowired
    private ICboMessageSysService cboMessageSysService;
    @Autowired
    private MpmCustomerTaskService mpmCustomerTaskService;
    @Autowired
    private MpmProjectTaskFeedbackService mpmProjectTaskFeedbackService;
    @Autowired
    private MpmProjectStakeholderService mpmProjectStakeholderService;
    @Autowired
    private MpmProjectSaleService mpmProjectSaleService;
    @Autowired
    private MpmProjectTaskHistoryService mpmProjectTaskHistoryService;
    /**
     * @author: wudaliang
     * @date: 2021-01-07
     * @param: entity
     * @description:
     * @return: void
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            if ((Long) entity.getValue("operatecode") == 0) {
                entity.setValue("operatecode", arrayId[0]);
            }
            //设置用户添加里程碑及任务赋值 sourcetype
            if(entity.getValue("sourcetype")==null){
                entity.setValue("sourcetype","user");
            }
            String docNo = String.valueOf(arrayId[0]);
            docNo = docNo.substring(0, 6) + docNo.substring(9);
            entity.setValue(MpmProjectMilepostEntity.FieldMilepostcode, docNo);
        }
    }

    @Override
    protected void afterInsert(BasicEntity entity) throws ServiceException {
        //刚插入的里程碑及任务enabled置为0，审批技术后enabled置为1
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" id = '{0}'", entity.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("enabled", 0);
        this.updateByWhere(map, sql.toString());
    }

    @Override
    protected void afterInsertBatch(List<BasicEntity> listEntity) throws ServiceException {
        // 刚插入的里程碑及任务enabled置为0，审批结束后enabled置为1
        String id = listEntity.stream().map(entity -> "'" + ConvertUtil.convertToString(entity.getId()) + "'")
                .collect(Collectors.joining(","));
        // 只有id不为空时才会执行update操作，防止sql报错
        if(!StringUtil.isEmpty(id)) {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" id in ({0})", id);
            HashMap<String, Object> map = new HashMap<>();
            map.put("enabled", 0);
            this.updateByWhere(map, sql.toString());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void deleteBefore(String whereSql) {
        if(whereSql.contains("planid")) {
            return;
        }
        List<MpmProjectMilepostEntity> mpmProjectMilepostEntityList = this
                .queryByWhere(whereSql);
        if (CollectionUtil.isEmpty(mpmProjectMilepostEntityList)) {
            return;
        }
        StringBufferProxy sql = new StringBufferProxy();
        StringBuffer string = new StringBuffer();
        for (MpmProjectMilepostEntity entity : mpmProjectMilepostEntityList
        ) {
            string.append(entity.getOperatecode());
            string.append(",");
            // 删除里程碑对应的督办
            sql.clear();
            sql.appendSingle(" enabled = 1 and superviseobjecttype = '{0}' and superviseobjectcode like '%{1}%' ", MpmSystemConst.MpmSuperviseObjectType.milepost, entity.getMilepostcode());
            mpmProjectSuperviseService.deleteByWhere(sql.toString());
        }
        // 删除里程碑下挂载任务
        String substring = string.substring(0, string.lastIndexOf(","));
        sql.clear();
        sql.appendSingle("milepostcode in ({0})", substring);
        List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService
                .queryByWhere(sql.toString());
        if (mpmProjectTaskEntities.size() > 0) {
            String delStr = mpmProjectTaskEntities.stream().map(item -> ConvertUtil.convertToString(item.getId())).collect(Collectors.joining(","));
            mpmProjectTaskService.deleteByIds(delStr);
        }
    }


    @SneakyThrows
    @Override
    protected void updateBefore(Map<String, Object> map) throws ServiceException {
        // 如果是不走审批单独变更一个里程碑(map中存有fromindex标记)，直接发送变更信息
        this.singleChangeSendMessage(map);
    }
    /**
     * @description:
     * @author xinfushuo
     * @param
     * @throws
     * @return
     * @date 2021/10/19
     * @modify
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(Map<String,Object> paraMap){

        //获取最新策划书id
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("enabled=1 and state = 0 and projectcode ='{0}' order by CREATEON desc",paraMap.get("projectcode"));
        List<MpmProjectPlanEntity> planNewEntities = mpmProjectPlanService
                .queryByWhere(sql.toString());
        sql.clear();
        //若获取不到策划书则直接返回
        if(planNewEntities.isEmpty()){
            return;
        }
        boolean taskFlag = this.judgeProjectALevel(planNewEntities.get(0).getProjectcode());
        // 若存在旧的策划书，为新策划书添加旧策划书客户决策分析和主要竞争对手分析信息
        sql.clear();
        sql.appendSingle("enabled=1 and state = 9 and projectcode ='{0}' order by CREATEON desc",paraMap.get("projectcode"));
        List<MpmProjectPlanEntity> planOldEntities = mpmProjectPlanService
                .queryByWhere(sql.toString());
        sql.clear();
        // 为新策划书添加旧策划书主要竞争对手分析
        if(planOldEntities.size() > 0) {
            generateRivalData(planOldEntities, planNewEntities);
        }
        // 若存在旧的策划书且项目为BCD级、A级（电商、其他）项目，生成客户决策信息子表
        if(planOldEntities.size() > 0 && !taskFlag) {
            generateCustomerData(planOldEntities, planNewEntities);
        }
        //若参数不为空，则为新策划书添加旧策划书里程碑及任务信息
        if (!ConvertUtil.convertToString(paraMap.get("oldmilepost")).equals("[]") && paraMap.get("oldmilepost") != null) {
            List<MpmProjectMilepostEntity> datalist = JSON
                    .parseArray(ConvertUtil.convertToString(paraMap.get("oldmilepost")),
                            MpmProjectMilepostEntity.class);
            // operatecode 为当前策划书里程碑及任务与旧策划书相同里程碑及任务的共同字段
            sql.appendSingle("enabled=0 and planid= '{0}' and  operatecode='{1}' ",
                    planNewEntities.get(0).getId(), datalist.get(0).getOperatecode());
            List<MpmProjectMilepostEntity> milepostentites = this
                    .queryByWhere(sql.toString());
            // 若存在旧里程碑及任务 且 新策划书未同步旧里程碑及任务
            if (datalist.size() != 0 && milepostentites.size() < 1) {
                List<BasicEntity> projectMilepostIns = new ArrayList<BasicEntity>();
                for (MpmProjectMilepostEntity data : datalist) {
                    data.setValue("id", 0);
                    data.setNewadd(0);
                    // 同步的里程碑及任务enabled值为0，当策划变更审批结束时enabled置为1
                    data.setEnabled(0);
                    data.setPlanid(planNewEntities.get(0).getId());
                    projectMilepostIns.add(data);
                }
                this.insertBatch(projectMilepostIns);
            }
            // 在策划变更第一次生成里程碑时，同步生成任务历史
            long planid = planNewEntities.get(0).getId();
            sql.clear();
            sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", paraMap.get("projectcode"));
            List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService.queryByWhere(sql.toString());
            List<BasicEntity> basicTaskHistory = new ArrayList<>();
            for (MpmProjectTaskEntity taskEntity : mpmProjectTaskEntities) {
                MpmProjectTaskHistoryEntity historyEntity = new MpmProjectTaskHistoryEntity();
                historyEntity.convertFromMap(taskEntity.convertToMap());
                historyEntity.setPlanid(planid);
                historyEntity.setTasksourceid(taskEntity.getId());
                basicTaskHistory.add(historyEntity);
            }
            mpmProjectTaskHistoryService.insertBatch(basicTaskHistory);
        }
    }
    /**
     * @param paraMap
     * @return
     * @Title: insert
     * @description:
     * @author: wudalaing
     * @date: 2021年1月12日下午5:25:05
     * @modify:
     */
    public ResponseResult insertFromProject(Map<String, Object> paraMap) {
        String projectcodeNew = ConvertUtil.convertToString(paraMap.get("projectcodenew"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode = '{0}'", projectcodeNew);
        List<MpmProjectEntity> mpmProjectEntities = this.mpmProjectService
                .queryByWhere(sql.toString());
        String ids = ConvertUtil.convertToString(paraMap.get("keys"));
        if (!StringUtil.isEmpty(ids)) {
            List<MpmProjectMilepostEntity> mpmProjectMilepostEntityList = this.queryByIds(ids);
            List<BasicEntity> projectMilepostIns = new ArrayList<BasicEntity>();
            for (MpmProjectMilepostEntity mpmProjectMilepostEntity : mpmProjectMilepostEntityList) {
                //赋值里程碑及任务初始字段
                mpmProjectMilepostEntity.setId(0);
                mpmProjectMilepostEntity.setMilepoststate(0);
                mpmProjectMilepostEntity.setMilepostcode("");
                mpmProjectMilepostEntity.setState(0);
                mpmProjectMilepostEntity.setPlanfinishtime(null);
                mpmProjectMilepostEntity.setActualfinishtime(null);
                mpmProjectMilepostEntity.setResponsible("");
                mpmProjectMilepostEntity.setResponsiblecode("");
                mpmProjectMilepostEntity.setSourceid(mpmProjectEntities.get(0).getId());
                mpmProjectMilepostEntity.setSourcetype("按项目添加");
                mpmProjectMilepostEntity.setDescription("");
                mpmProjectMilepostEntity.setOperatecode(0);
                mpmProjectMilepostEntity.setPlanid(ConvertUtil.convertToLong(paraMap.get("planid")));
                mpmProjectMilepostEntity.setEnabled(0);
//                MpmProjectMilepostEntity.setLatestphase("");
//                MpmProjectMilepostEntity.setDocno("");
//                MpmProjectMilepostEntity.setDocdate(new Date());
//                MpmProjectMilepostEntity.setTaskschedule("0");
//                MpmProjectMilepostEntity.setMilepostcode("0");
//                MpmProjectMilepostEntity.setMilepostname("");
                mpmProjectMilepostEntity.setProjectcode(projectcodeNew);
//                MpmProjectMilepostEntity.setActualstartdate(null);
//                MpmProjectMilepostEntity.setActualenddate(null);
//                MpmProjectMilepostEntity.setApplyorgcode(this.getSessionUserBean().getOrg().getCode());
//                MpmProjectMilepostEntity.setApplydeptcode(this.getSessionUserBean().getDept().getCode());
//                MpmProjectMilepostEntity.setOrgcode(this.getSessionUserBean().getOrg().getCode());
//                MpmProjectMilepostEntity.setDeptcode(this.getSessionUserBean().getDept().getCode());
//                MpmProjectMilepostEntity.setUsercode(this.getSessionUserBean().getUser().getCode());
//                MpmProjectMilepostEntity.setUsername(this.getSessionUserBean().getUser().getName());
//                MpmProjectMilepostEntity.setApplyusercode(this.getSessionUserBean().getUser().getCode());
//                MpmProjectMilepostEntity.setApplyusername(this.getSessionUserBean().getUser().getName());
                projectMilepostIns.add(mpmProjectMilepostEntity);
            }
            this.insertBatch(projectMilepostIns);
            return ResponseResult.ok("插入任务成功，共 " + mpmProjectMilepostEntityList.size() + "条。");
        } else {
            return ResponseResult.ok("没有可插入的任务数据，请确认勾选相关任务！");
        }
    }

    /**
     * @author: wudaliang
     * @date: 2021-01-21
     * @param: paraMap keys 模板对应id projectcode 项目编号 planid 策划书id
     * @description: 按照模板添加里程碑及任务
     * @return: com.topscomm.pub.vo.ResponseResult
     * @modify:
     */
    public ResponseResult insertFromMilePostTemplate(Map<String, Object> paraMap) {
        String milepostids = ConvertUtil.convertToString(paraMap.get("milepostids"));
        String taskids = ConvertUtil.convertToString(paraMap.get("taskids"));
        String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        String projectname = ConvertUtil.convertToString(paraMap.get("projectname"));
        long planid = ConvertUtil.convertToLong(paraMap.get("planid") );
        if (StringUtil.isEmpty(milepostids)) {
            return ResponseResult.ok("没有可插入的里程碑及任务数据，请确认勾选相关里程碑及任务！");
        }
        StringBufferProxy sqlForMilepost = new StringBufferProxy();
        sqlForMilepost.appendSingle(" id in ({0}) order by sortcode ",milepostids);
        List<MpmMilePostTemplateEntity> mpmMilePostTemplateEntities = mpmMilePostTemplateService
                .queryByWhere(sqlForMilepost.toString());
        for (MpmMilePostTemplateEntity mpmMilePostTemplateEntity : mpmMilePostTemplateEntities) {
            MpmProjectMilepostEntity mpmProjectMilepostEntity = new MpmProjectMilepostEntity();

            //赋值里程碑及任务初始字段
            mpmProjectMilepostEntity.setId(0);
            mpmProjectMilepostEntity.setMilepostcode("0");
            mpmProjectMilepostEntity.setPlanfinishtime(null);
            mpmProjectMilepostEntity.setActualfinishtime(null);
            mpmProjectMilepostEntity.setMilepoststate(0);
            mpmProjectMilepostEntity.setOperatecode(0);
            mpmProjectMilepostEntity.setSourcetype(MpmMilePostTemplateEntity.tableName);
            mpmProjectMilepostEntity.setResponsible("");
            mpmProjectMilepostEntity.setResponsiblecode("");
            mpmProjectMilepostEntity.setState(0);
            mpmProjectMilepostEntity.setNewadd(1);
            //赋值拷贝字段
            mpmProjectMilepostEntity.setMilepostname(mpmMilePostTemplateEntity.getName());
            mpmProjectMilepostEntity.setDeliverable(mpmMilePostTemplateEntity.getDeliverable());
            mpmProjectMilepostEntity.setProjectcode(projectcode);
            mpmProjectMilepostEntity.setSourceid(mpmMilePostTemplateEntity.getId());
            mpmProjectMilepostEntity.setPlanid(planid);
            this.insert(mpmProjectMilepostEntity);
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle("MILEPOSTTEMPLATEID = '{0}' order by sortcode ",mpmMilePostTemplateEntity.getId());
            List<MpmProjectTaskTemplateEntity> mpmProjectTaskTemplateEntities = mpmProjectTaskTemplateService.queryByWhere(sql.toString());
            List<BasicEntity> projectTaskIns = new ArrayList<BasicEntity>();
            int index = 1;
            for(MpmProjectTaskTemplateEntity projectTaskTemplateEntity : mpmProjectTaskTemplateEntities) {
                // 如果模板里程碑下的这个任务用户选中了，进行新增操作
                if (!("," + taskids + ",").contains("," + projectTaskTemplateEntity.getId() + ",")) {
                    continue;
                }
                MpmProjectTaskEntity mpmProjectTaskEntity = new MpmProjectTaskEntity();
                mpmProjectTaskEntity.setTaskname(projectTaskTemplateEntity.getTaskname());
                mpmProjectTaskEntity.setTaskdetail(projectTaskTemplateEntity.getTaskdetail());
                mpmProjectTaskEntity.setState(0);
                mpmProjectTaskEntity.setProjectcode(mpmProjectMilepostEntity.getProjectcode());
                mpmProjectTaskEntity.setProjectname(projectname);
                mpmProjectTaskEntity.setMilepostcode(ConvertUtil.convertToString(mpmProjectMilepostEntity.getOperatecode()));
                mpmProjectTaskEntity.setMilepostname(mpmProjectMilepostEntity.getMilepostname());
                mpmProjectTaskEntity.setTaskstate("0");
                mpmProjectTaskEntity.setApplyorgcode(this.getSessionUserBean().getOrg().getCode());
                mpmProjectTaskEntity.setApplydeptcode(this.getSessionUserBean().getDept().getCode());
                mpmProjectTaskEntity.setOrgcode(this.getSessionUserBean().getOrg().getCode());
                mpmProjectTaskEntity.setDeptcode(this.getSessionUserBean().getDept().getCode());
                mpmProjectTaskEntity.setUsercode(this.getSessionUserBean().getUser().getCode());
                mpmProjectTaskEntity.setUsername(this.getSessionUserBean().getUser().getName());
                mpmProjectTaskEntity.setApplyusercode(this.getSessionUserBean().getUser().getCode());
                mpmProjectTaskEntity.setApplyusername(this.getSessionUserBean().getUser().getName());
                mpmProjectTaskEntity.setTaskcode(ConvertUtil.convertToString(mpmProjectMilepostEntity.getSortcode()+"-"+index));
                mpmProjectTaskEntity.setTaskschedule("0");
                mpmProjectTaskEntity.setTaskexplain(projectTaskTemplateEntity.getTaskexplain());
                mpmProjectTaskEntity.setIstemplate("1");
                mpmProjectTaskEntity.setTasktemplateid(projectTaskTemplateEntity.getId());
                mpmProjectTaskEntity.setIsneedcustomer(projectTaskTemplateEntity.getIsneedcustomer());
                // 如果是招标项目，赋值任务模板dmdtask的值，非招标项目都赋值0,履约评价/运行绩效得分任务，国网赋值为2，南网赋值为4，其他赋值为0
                if (this.whetherBidProject(projectcode)) {
                    // 如果为履约评价任务，需要判断是否为南网、国网,南网赋值为2,国网赋值为4,其他赋值为0
                    if (projectTaskTemplateEntity.getDmdtask() == MpmSystemConst.DmdTask.IsPerformance) {
                        this.getDmdTaskCode(mpmProjectTaskEntity);
                    } else {
                        mpmProjectTaskEntity.setDmdtask(projectTaskTemplateEntity.getDmdtask());
                    }
                } else {
                    mpmProjectTaskEntity.setDmdtask(MpmSystemConst.DmdTask.Notdmd);
                }
                index++;
                projectTaskIns.add(mpmProjectTaskEntity);
            }
            mpmProjectTaskService.insertBatch(projectTaskIns);
        }
        return ResponseResult.ok("插入里程碑及任务成功，共 " + mpmMilePostTemplateEntities.size() + "条。");
    }
    /**
     * @description:
     * @author xinfushuo
     * @param
     * @throws
     * @return
     * @date 2021/10/18
     * @modify
     */
    public List<Map<String,Object>> queryTaskListForBidGuide(String projectCode){
        return new ArrayList<>();
    }
    /**
     * @author houyuhang
     * @Description 首页里程碑及任务超期
     * @Date 2021/11/29
     * @return Map<String,Object>
     **/
    @Override
    public Map<String,Object> queryOverdueMilepost(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        Map<String, Object> overdueMilepostResult = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormat = simpleDateFormat.format(new Date());
        // 查询未完成且已超期的里程碑及任务
        sql.appendSingle(" MPMPROJECTMILEPOST.PLANFINISHTIME< {0} and " +
                        "MPMPROJECTMILEPOST.MILEPOSTSTATE = '{1}' and MPMPROJECTMILEPOST.enabled = 1 ",
                SQLAdapter.toDateShort(dateFormat), MpmSystemConst.MilepostStateCode.MilepostIncompleteCode);
        sql.appendSingle(" and {0} ", mpmProjectService.whereExistsSqlForIndex(MpmProjectMilepostEntity.tableName,
                MpmProjectMilepostEntity.FieldProjectcode, ConvertUtil.convertToString(paraMap.get("dataPermissionFlag"))));
        int countMilpost = this.getCount(sql.toString());
        overdueMilepostResult.put("code", "overdueMilepostNum");
        overdueMilepostResult.put("name", "超期里程碑及任务");
        overdueMilepostResult.put("iconImg", "/static/images/paojectManager/overdueMilepostFlag.png");
        overdueMilepostResult.put("value", countMilpost);
        return overdueMilepostResult;
    }

    /**
     * @author zhangjunyao
     * @Description 联表查询督办情况（项目监管页面用）
     * @Date 2021/12/13
     * @return
     **/
    @Transactional
    public void getSuperviseList(List<Map<String, Object>> tempList, String projectCode) {
        // 查询的里程碑及任务只属于一个项目
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode = '{0}' and {1} = '2'", projectCode, MpmProjectSuperviseEntity.FieldSuperviseobjecttype);
        List<Map<String, Object>> superviseList = mpmProjectSuperviseService.queryMapByWhere(sql.toString());
        for (Map<String, Object> mapRow : tempList) {
            String milepostName = ConvertUtil.convertToString(mapRow.get(MpmProjectMilepostEntity.FieldMilepostname));
            for (Map<String, Object> superviseMap : superviseList) {
                String superviseObject = ConvertUtil.convertToString(superviseMap.get(MpmProjectSuperviseEntity.FieldSuperviseobject));
                List<String> superviseObjectList = Arrays.stream(superviseObject.split("，")).collect(Collectors.toList());
                if (superviseObjectList.contains(milepostName)) {
                    mapRow.put("supervise", superviseMap);
                }
            }
        }
    }

    /**
     * @author zhangjunyao
     * @Description 联表查询里程碑及任务项目相关信息（超期里程碑及任务用）
     * @Date 2021/12/14
     * @return
     **/
    @Transactional
    public void getProjectInfo(List<Map<String, Object>> tempList) {
        String projectCodes = tempList.stream().map(map -> ConvertUtil.convertToString(map.get("projectcode")))
                .collect(Collectors.joining("','", "'", "'"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode in ({0})", projectCodes);
        List<MpmProjectEntity> projectEntities = mpmProjectService.queryByWhere(sql.toString());
        if (CollectionUtils.isEmpty(projectEntities)) {
            return;
        }
        Map<String, MpmProjectEntity> resultMap = projectEntities.stream().collect(Collectors.toMap(
                MpmProjectEntity::getProjectcode, mpmProjectEntity -> mpmProjectEntity, (v1, v2) -> v1));
        for (Map<String, Object> mapRow : tempList) {
            String projectCode = ConvertUtil.convertToString(mapRow.get("projectcode"));
            if (resultMap.containsKey(projectCode)) {
                MpmProjectEntity mpmProjectEntity = resultMap.get(projectCode);
                mapRow.put("projectname", mpmProjectEntity.getProjectname());
                mapRow.put("deptname", mpmProjectEntity.getDeptname());
                String projectlevel = mpmProjectEntity.getProjectlevel();
                mapRow.put("dispprojectlevel", datacodeCache.getValueDynamic("MpmProjectLevel", projectlevel,
                        "code", "name"));
                mapRow.put("projectmanager", mpmProjectEntity.getProjectmanager());
            }
        }
    }

    /**
     * @author zhangjunyao
     * @Description 联表查询里程碑及任务未完成任务（超期里程碑及任务用）
     * @Date 2021/12/14
     * @return
     **/
    @Transactional
    public void getUnfinishedTask(List<Map<String, Object>> tempList) {
        String milepostIds = tempList.stream().map(map -> ConvertUtil.convertToString(map.get(MpmProjectMilepostEntity.FieldOperatecode)))
                .collect(Collectors.joining("','", "'", "'"));
        StringBufferProxy sql = new StringBufferProxy();
        // 获取创建时间最早的未完成任务（处于未开始、进行中、冻结状态的任务），按创建时间倒序排序
        sql.appendSingle("milepostcode in ({0}) and taskstate in (0,1,-1) and enabled = 1 order by createon desc", milepostIds);
        List<MpmProjectTaskEntity> taskEntities = mpmProjectTaskService.queryByWhere(sql.toString());
        if (CollectionUtils.isEmpty(taskEntities)) {
            for (Map<String, Object> mapRow : tempList) {
                mapRow.put("unfinishedtask", "暂无未完成的任务");
            }
            return;
        }
        Map<String, List<MpmProjectTaskEntity>> resultMap = taskEntities.stream().collect(Collectors.groupingBy(
                entity -> entity.getMilepostcode()));
        for (Map<String, Object> mapRow : tempList) {
            String operateCode = ConvertUtil.convertToString(mapRow.get(MpmProjectMilepostEntity.FieldOperatecode));
            if (resultMap.containsKey(operateCode)) {
                List<MpmProjectTaskEntity> mpmProjectTaskEntities = resultMap.get(operateCode);
                // 获取创建时间最早的未完成任务
                mapRow.put("unfinishedtask", mpmProjectTaskEntities.get(0).getTaskname());
            } else {
                mapRow.put("unfinishedtask", "暂无未完成的任务");
            }
        }
    }

    /**
     * @Title:
     * @description: 任务下发完成后给里程碑及任务责任人发送消息提醒
     * @param
     * @return
     * @author: zhangjunyao
     * @date: 2021年12月14日
     * @modify:
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendMessageToMilepostResponsible(String milepostCodes) {
        // 无任务下发时，milepostCodes为空，直接返回
        if (milepostCodes.equals("")) {
            return;
        }
        // 查询该策划书下所有里程碑及任务
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0} in ({1}) and {2} = 1 ", MpmProjectMilepostEntity.FieldOperatecode, milepostCodes, MpmProjectMilepostEntity.FieldEnabled);
        List<MpmProjectMilepostEntity> mpmProjectMilepostEntities = this.queryByWhere(sql.toString());
        if (CollectionUtil.isEmpty(mpmProjectMilepostEntities)) {
            return;
        }
        // 查询该项目立项信息
        sql.clear();
        sql.appendSingle(" {0} = '{1}' ", MpmProjectEntity.FieldProjectcode, mpmProjectMilepostEntities.get(0).getProjectcode());
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
        if (ObjectUtil.isEmpty(mpmProjectEntity)) {
            return;
        }
        // 配置消息标题内容
        String projectLevel = datacodeCache.getValueDynamic("MpmProjectLevel", mpmProjectEntity.getProjectlevel(), "code", "name");
        String title = "销售项目任务派发提醒";
        // 用于封装消息，批量插入
        List<Map<String, Object>> appList = new ArrayList<>(), sysList = new ArrayList<>();
        Map<String, Object> appMap = new HashMap<>(), sysMap = new HashMap<>();
        for(MpmProjectMilepostEntity mpmProjectMilepostEntity : mpmProjectMilepostEntities) {
            // 获取任务名称，封装消息内容
            StringBufferProxy content = new StringBufferProxy();
            content.appendSingle("您所负责的【{0}级项目：{1}】“{2}”里程碑及任务下所有任务已派发。", projectLevel, mpmProjectEntity.getProjectname(), mpmProjectMilepostEntity.getMilepostname());
            // app推送
            appMap = MessageUtil.createMessageAppMap(mpmProjectMilepostEntity.getResponsiblecode(), title, content.toString(), mpmProjectEntity.getId(),
                    MpmProjectMilepostEntity.tableName, 0);
            // 系统消息
            sysMap = MessageUtil.createMessageSysMap(mpmProjectMilepostEntity.getResponsiblecode(), mpmProjectMilepostEntity.getResponsible(), title, content.toString(),
                    mpmProjectEntity.getId(), MpmProjectMilepostEntity.tableName);
            // 封装
            appList.add(appMap);
            sysList.add(sysMap);
        }
        // 消息批量插入
        cboMessageAppService.insertList(appList);
        cboMessageSysService.insertList(sysList);
    }
    /**
     * @author houyuhang
     * @Description 判断项目是否为A级（非电商、其他）项目
     * @Date 2021/12/14
     * @return
     **/
    public boolean judgeProjectALevel(String projectcode) {
        StringBufferProxy sql = new StringBufferProxy();
        String purchasePattern = MpmSystemConst.PurchasePattern.chanpinBid + "," + MpmSystemConst.PurchasePattern.fuwuBid + "," + MpmSystemConst.PurchasePattern.dianshang;
        sql.appendSingle(" projectcode = '{0}' and projectlevel = '{1}' and {2} in ({3}) ",
                projectcode, MpmSystemConst.ProjectLevel.A, MpmProjectSaleEntity.FieldPurchasepattern, purchasePattern);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("whereSql",sql.toString());
        int count = mpmProjectService.getCount(dataMap,"projectALevel");
        return count > 0;
    }
    /**
     * @author houyuhang
     * @Description 策划变更BCD级项目生成客户决策分析
     * @Date 2022/03/11
     * @return
     **/
    @Transactional
    public void generateCustomerData(List<MpmProjectPlanEntity> planOldEntities, List<MpmProjectPlanEntity> planNewEntities) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" planid = '{0}' ", planOldEntities.get(0).getId());
        List<MpmCustomerAnalysisEntity> dataList = mpmCustomerAnalysisService.queryByWhere(sql.toString());
        sql.clear();
        sql.appendSingle(" planid = '{0}' ", planNewEntities.get(0).getId());
        List<MpmCustomerAnalysisEntity> newDataList = mpmCustomerAnalysisService.queryByWhere(sql.toString());
        sql.clear();
        if (newDataList.size() == 0 && dataList.size()>0) {
            List<BasicEntity> customerAnalysisIns = new ArrayList<BasicEntity>();
            for (MpmCustomerAnalysisEntity data : dataList) {
                data.setValue("id", 0);
                data.setPlanid(planNewEntities.get(0).getId());
                customerAnalysisIns.add(data);
            }
            mpmCustomerAnalysisService.insertBatch(customerAnalysisIns);
        }
    }
    /**
     * @author houyuhang
     * @Description 策划变更BCD级项目生成主要竞争对手分析
     * @Date 2022/03/11
     * @return
     **/
    @Transactional
    public void generateRivalData(List<MpmProjectPlanEntity> planOldEntities, List<MpmProjectPlanEntity> planNewEntities) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" planid = '{0}' ", planOldEntities.get(0).getId());
        List<MpmProjectCompetitorEntity> comDataList = mpmProjectCompetitorService.queryByWhere(sql.toString());
        sql.clear();
        sql.appendSingle(" planid = '{0}' ", planNewEntities.get(0).getId());
        List<MpmProjectCompetitorEntity> newComDataList = mpmProjectCompetitorService.queryByWhere(sql.toString());
        sql.clear();
        if (newComDataList.size() == 0 && comDataList.size()>0) {
            List<BasicEntity> projectCompetitorIns = new ArrayList<BasicEntity>();
            for (MpmProjectCompetitorEntity comData : comDataList) {
                comData.setValue("id", 0);
                comData.setPlanid(planNewEntities.get(0).getId());
                projectCompetitorIns.add(comData);
            }
            mpmProjectCompetitorService.insertBatch(projectCompetitorIns);
        }
    }

    /**
     * @author: zhangjunyao
     * @date: 2022-03-26
     * @description: 查询是否还有其他有效、已超期且未达成的里程碑及任务
     * @modify:
     */
    public Boolean checkMilepostOverDue(String projectCode) {
        Boolean isMilepostOverDue = false;
        StringBufferProxy sql = new StringBufferProxy();
        // 查询项目中所有有效、已超期且未达成的里程碑及任务
        sql.appendSingle(" {0} = '{1}' and {2} = {3} and {4} < {5} and enabled = 1 ", MpmProjectMilepostEntity.FieldProjectcode,
                projectCode, MpmProjectMilepostEntity.FieldMilepoststate, Integer.parseInt(MpmSystemConst.MilepostStateCode.MilepostIncompleteCode),
                MpmProjectMilepostEntity.FieldPlanfinishtime, SQLAdapter.toDateShort(DateUtil.formatDate(new Date())));
        int count = this.getCount(sql.toString());
        if (count > 0) {
            isMilepostOverDue = true;
        }
        return isMilepostOverDue;
    }

    /***
     * @description: 保存策划套用之前项目套用信息
     * @param paraMap
     * @return void
     * @author: wangxinhua
     * @date: 2022/9/14 16:12
     * @modify:
     */
    @Override
    public void saveOldProjectInfo(Map<String, Object> paraMap) {
        String milePostCodes = ConvertUtil.convertToString(paraMap.get("milePostCodes"));
        String projectCode = ConvertUtil.convertToString(paraMap.get("projectCode"));
        String projectName = ConvertUtil.convertToString(paraMap.get("projectName"));
        String taskIds = ConvertUtil.convertToString(paraMap.get("taskIds"));
        long planId = ConvertUtil.convertToLong(paraMap.get("planId") );

        if (!StringUtil.isEmpty(milePostCodes)) {
            //获取套用的里程碑
            StringBufferProxy sqlForMilepost = new StringBufferProxy();
            sqlForMilepost.appendSingle(" operatecode in ({0}) and enabled=1 order by sortcode ",milePostCodes);
            List<MpmProjectMilepostEntity> mpmProjectMilepostEntities = this.queryByWhere(sqlForMilepost.toString());
            for (MpmProjectMilepostEntity itemMilePost : mpmProjectMilepostEntities) {
                MpmProjectMilepostEntity mpmProjectMilepostEntity = new MpmProjectMilepostEntity();

                //赋值里程碑及任务初始字段
                mpmProjectMilepostEntity.setId(0);
                mpmProjectMilepostEntity.setMilepostcode("0");
                mpmProjectMilepostEntity.setMilepoststate(0);
                mpmProjectMilepostEntity.setOperatecode(0);
                mpmProjectMilepostEntity.setCopysourcetype(MpmProjectMilepostEntity.tableName);
                mpmProjectMilepostEntity.setCopysourceid(itemMilePost.getId());
                mpmProjectMilepostEntity.setSourcetype(itemMilePost.getSourcetype());
                mpmProjectMilepostEntity.setSourceid(itemMilePost.getSourceid());
                mpmProjectMilepostEntity.setResponsible("");
                mpmProjectMilepostEntity.setResponsiblecode("");
                mpmProjectMilepostEntity.setState(0);
                mpmProjectMilepostEntity.setNewadd(1);
                //赋值拷贝字段
                mpmProjectMilepostEntity.setMilepostname(itemMilePost.getMilepostname());
                mpmProjectMilepostEntity.setDeliverable(itemMilePost.getDeliverable());
                mpmProjectMilepostEntity.setSortCode(itemMilePost.getSortcode());
                mpmProjectMilepostEntity.setProjectcode(projectCode);
                mpmProjectMilepostEntity.setPlanid(planId);
                mpmProjectMilepostEntity.setCopyedit("0");
                this.insert(mpmProjectMilepostEntity);
                //获取套用的任务
                StringBufferProxy sql = new StringBufferProxy();
                sql.appendSingle(" id in ({0}) and milepostcode='{1}' and enabled=1 order by sortcode asc,planenddate asc,planstartdate asc,id asc ", taskIds, itemMilePost.getOperatecode());
                List<MpmProjectTaskEntity> mpmProjectTasks = mpmProjectTaskService.queryByWhere(sql.toString());
                List<BasicEntity> projectTaskIns = new ArrayList<BasicEntity>();
                int index = 1;
                for(MpmProjectTaskEntity itemProjectTask : mpmProjectTasks) {
                    MpmProjectTaskEntity mpmProjectTaskEntity = new MpmProjectTaskEntity();
                    mpmProjectTaskEntity.setTaskname(itemProjectTask.getTaskname());
                    mpmProjectTaskEntity.setTaskdetail(itemProjectTask.getTaskdetail());
                    mpmProjectTaskEntity.setState(0);
                    mpmProjectTaskEntity.setProjectcode(projectCode);
                    mpmProjectTaskEntity.setProjectname(projectName);
                    mpmProjectTaskEntity.setMilepostcode(ConvertUtil.convertToString(mpmProjectMilepostEntity.getOperatecode()));
                    mpmProjectTaskEntity.setMilepostname(mpmProjectMilepostEntity.getMilepostname());
                    mpmProjectTaskEntity.setTaskstate("0");
                    mpmProjectTaskEntity.setApplyorgcode(this.getSessionUserBean().getOrg().getCode());
                    mpmProjectTaskEntity.setApplydeptcode(this.getSessionUserBean().getDept().getCode());
                    mpmProjectTaskEntity.setOrgcode(this.getSessionUserBean().getOrg().getCode());
                    mpmProjectTaskEntity.setDeptcode(this.getSessionUserBean().getDept().getCode());
                    mpmProjectTaskEntity.setUsercode(this.getSessionUserBean().getUser().getCode());
                    mpmProjectTaskEntity.setUsername(this.getSessionUserBean().getUser().getName());
                    mpmProjectTaskEntity.setApplyusercode(this.getSessionUserBean().getUser().getCode());
                    mpmProjectTaskEntity.setApplyusername(this.getSessionUserBean().getUser().getName());
                    mpmProjectTaskEntity.setTaskcode(ConvertUtil.convertToString(mpmProjectMilepostEntity.getSortcode()+"-"+index));
                    mpmProjectTaskEntity.setTaskschedule("0");
                    mpmProjectTaskEntity.setTaskexplain(itemProjectTask.getTaskexplain());
                    mpmProjectTaskEntity.setIstemplate(itemProjectTask.getIstemplate());
                    mpmProjectTaskEntity.setTasktemplateid(itemProjectTask.getId());
                    mpmProjectTaskEntity.setIsneedcustomer(itemProjectTask.getIsneedcustomer());
                    mpmProjectTaskEntity.setDmdtask(itemProjectTask.getDmdtask());
                    mpmProjectTaskEntity.setTasktarget(itemProjectTask.getTasktarget());
                    mpmProjectTaskEntity.setSortCode(itemProjectTask.getSortcode());
                    mpmProjectTaskEntity.setCopyedit("0");
                    mpmProjectTaskEntity.setCopysourceid(itemProjectTask.getId());
                    mpmProjectTaskEntity.setCopysourcetype(MpmProjectTaskEntity.tableName);
                    index++;
                    projectTaskIns.add(mpmProjectTaskEntity);
                }
                mpmProjectTaskService.insertBatch(projectTaskIns);
            }
        }
    }
    /***
     * @description: 是否为招标项目
     * @param projectcode
     * @return boolean
     * @author: houyuhang
     * @date: 2022/11/14
     * @modify:
     */
    public boolean whetherBidProject(String projectcode) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" purchasepattern in ({0}) and projectcode = '{1}' ", MpmSystemConst.PurchasePattern.chanpinBid + "," + MpmSystemConst.PurchasePattern.fuwuBid + "," + MpmSystemConst.PurchasePattern.dianshang, projectcode);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("whereSql", sql.toString());
        int count = mpmProjectService.getCount(dataMap, "projectALevel");
        return count > 0;
    }
    /***
     * @description: 南网、国网项目
     * @return void
     * @author: houyuhang
     * @date: 2022/12/02
     * @modify:
     */
    public void getDmdTaskCode(MpmProjectTaskEntity mpmProjectTaskEntity) {
        String projectcode = mpmProjectTaskEntity.getProjectcode();
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", projectcode);
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
        // 获取项目的deptcommoncode，区分国网、南网和其他
        String deptcommoncode = mpmProjectEntity.getDeptcommoncode();
        String realdeptcommoncode = "";
        List<Map<String, Object>> deptList = datacodeCache.getCodeListMap("LtcDeptDifferenceGrid", "", "sortcode");
        for (Map<String, Object> deptMap : deptList) {
            if (("," + deptMap.get("code") + ",").contains("," + deptcommoncode + ",")) {
                realdeptcommoncode = ConvertUtil.convertToString(deptMap.get("name"));
                break;
            }
        }
        if ("1".equals(realdeptcommoncode)) {
            mpmProjectTaskEntity.setDmdtask(MpmSystemConst.DmdTask.IsPerformance);
        } else if ("2".equals(realdeptcommoncode)) {
            mpmProjectTaskEntity.setDmdtask(MpmSystemConst.DmdTask.IsNanwangPerformance);
        } else {
            mpmProjectTaskEntity.setDmdtask(MpmSystemConst.DmdTask.Notdmd);
        }
    }
    /***
     * @description: 发送里程碑单独修改消息
     * @return void
     * @author: houyuhang
     * @date: 2023/02/11
     * @modify:
     */
    public void singleChangeSendMessage(Map<String, Object> map) throws Exception {
        // 如果是不走审批单独变更一个里程碑(map中存有fromindex标记)，直接发送变更信息
        if (!map.containsKey("fromindex")) {
            return;
        }
        MpmProjectMilepostEntity oldEntity = this.queryById(ConvertUtil.convertToString(map.get("id")));
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(" projectcode='" + oldEntity.getProjectcode() + "'");
        if (ObjectUtil.isEmpty(oldEntity) || ObjectUtil.isEmpty(mpmProjectEntity)) {
            return;
        }
        // 使用basechangelog表获取变更内容
        Map<String, Object> changeMap = new HashMap<String, Object>();
        changeMap.put("topsourcetype", MpmProjectPlanEntity.tableName);
        changeMap.put("topsourceid", ConvertUtil.convertToString(map.get("planid")));
        changeMap.put("sourcetype", MpmProjectMilepostEntity.tableName);
        changeMap.put("sourceid", ConvertUtil.convertToString(map.get("id")));
        changeMap.put("newmap", map);
        changeMap.put("oldmap", oldEntity.convertToMap());
        changeMap.put("baselogoperatetype", MpmSystemConst.BaseLogOperateTypeEnum.Edit);
        changeMap.put("version", "1");
        Map<String, Object> changeResMap = this.getMainChangeLogEntity(changeMap);
        if (ObjectUtil.isEmpty(changeResMap)) {
            return;
        }
        // 获取需要发送消息的人员(里程碑为里程碑责任人、项目经理且剔除发起修改的人、任务为任务责任人、里程碑责任人、项目经理且剔除发起修改的人)
        List<Map<String, String>> receiverList = this.queryMessageUser(map, mpmProjectEntity, ConvertUtil.convertToString(map.get("singlechangeuser")), MpmProjectMilepostEntity.tableName);
        if (CollectionUtil.isEmpty(receiverList)) {
            return;
        }
        String title = "销售项目里程碑变更通知";
        String projectLevel = datacodeCache.getValueDynamic("MpmProjectLevel", mpmProjectEntity.getProjectlevel(), "code", "name");
        StringBufferProxy content = new StringBufferProxy();
        content.appendSingle("【{0}级项目：{1}】{2}里程碑：{3}请知悉。", projectLevel, mpmProjectEntity.getProjectname(), ConvertUtil.convertToString(map.get("milepostname")), this.getMilepostInfoDetail(changeResMap));
        List<Map<String, Object>> appList = new ArrayList<>(), sysList = new ArrayList<>();
        for (Map<String, String> receiver : receiverList) {
            appList.add(MessageUtil.createMessageAppMap(ConvertUtil.convertToString(receiver.get("usercode")), title, content.toString(), mpmProjectEntity.getId(),
                    MpmProjectPlanEntity.tableName, 0));
            sysList.add(MessageUtil.createMessageSysMap(ConvertUtil.convertToString(receiver.get("usercode")), ConvertUtil.convertToString(receiver.get("username")), title, content.toString(),
                    mpmProjectEntity.getId(), MpmProjectPlanEntity.tableName));
        }
        cboMessageAppService.insertList(appList);
        cboMessageSysService.insertList(sysList);
    }
    /***
     * @description: 获取里程碑变更修改具体字段
     * @return
     * @author: houyuhang
     * @date: 2023/02/06
     * @modify:
     */
    public String getMilepostInfoDetail(Map<String, Object> changeResMap) {
        List<String> listStr = new ArrayList<>();
        JSONArray jsonArray = JSONArray.parseArray(ConvertUtil.convertToString(changeResMap.get("content")));
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            listStr.add(jsonObject.getString("name"));
        }
        return listStr.stream().collect(Collectors.joining("、")) + "已变更，";
    }
    /***
     * @description: 获取里程碑变更修改具体字段
     * @return
     * @author: houyuhang
     * @date: 2023/02/11
     * @modify:
     */
    public List<Map<String, String>> queryMessageUser(Map<String, Object> map, MpmProjectEntity mpmProjectEntity, String excludeUser, String sourcetype) {
        Set<String> userCodeList = new HashSet<>();
        Map<String, String> userRef = new HashMap<>();
        List<Map<String, String>> receiverList = new ArrayList<>();
        // 获取用户信息
        userCodeList.add(ConvertUtil.convertToString(map.get("responsiblecode")));
        userRef.put(ConvertUtil.convertToString(map.get("responsiblecode")), ConvertUtil.convertToString(map.get("responsible")));
        userCodeList.add(mpmProjectEntity.getProjectmanagercode());
        userRef.put(mpmProjectEntity.getProjectmanagercode(), mpmProjectEntity.getProjectmanager());
        // 如果是任务，额外获取里程碑责任人信息
        if (MpmProjectTaskEntity.tableName.equals(sourcetype)) {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" enabled = 1 and operatecode = '{0}' ", ConvertUtil.convertToString(map.get("milepostcode")));
            MpmProjectMilepostEntity mpmProjectMilepostEntity = this.queryObjectByWhere(sql.toString());
            if (!ObjectUtil.isEmpty(mpmProjectMilepostEntity)) {
                userCodeList.add(mpmProjectMilepostEntity.getResponsiblecode());
                userRef.put(mpmProjectMilepostEntity.getResponsiblecode(), mpmProjectMilepostEntity.getResponsible());
            }
        }
        // 剔除发起变更人员
        userCodeList.remove(excludeUser);
        if (CollectionUtil.isEmpty(userCodeList)) {
            return new ArrayList<>();
        }
        for (String usercode : userCodeList) {
            Map<String, String> tempMap = new HashMap<>();
            tempMap.put("usercode", usercode);
            tempMap.put("username", userRef.get(usercode));
            receiverList.add(tempMap);
        }
        return receiverList;
    }
    /***
     * @description: 自定义输入，存入来自前台的字段planid和projectcode
     * @return void
     * @author: houyuhang
     * @date: 2023/02/14
     * @modify:
     */
    public void expandInputExcelData(List<Map<String, String>> listDataMap, Map<String, Object> paraMap, StringBufferProxy throwStringMessage) {
        String planid = ConvertUtil.convertToString(paraMap.get("planid"));
        String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        if (StringUtil.isEmpty(planid) || StringUtil.isEmpty(projectcode)) {
            throw new ServiceException("项目编号不存在，请联系管理员！");
        }
        for (Map<String, String> listMap : listDataMap) {
            listMap.put("planid", planid);
            listMap.put("projectcode", projectcode);
        }
    }
    /***
     * @description: 完成里程碑信息赋值
     * @return void
     * @author: houyuhang
     * @date: 2023/02/14
     * @modify:
     */
    public void expandProcessExcelData(List<Map<String, String>> list, StringBufferProxy throwStringMessage) {
        int count = 1;
        for (int i = 0; i < list.size() ; i++) {
            Map<String, String> map = list.get(i);
            // 格式化日期
            if (map.containsKey("planfinishtime")) {
                map.put("planfinishtime", this.formatVariousDate(map.get("planfinishtime")));
            }
            if (map.containsKey("planstartdate")) {
                map.put("planstartdate", this.formatVariousDate(map.get("planstartdate")));
            }
            if (map.containsKey("planenddate")) {
                map.put("planenddate", this.formatVariousDate(map.get("planenddate")));
            }
            if (i == 0 || !StringUtil.isEmpty(map.get(MpmProjectMilepostEntity.FieldMilepostname))) {
                map.put("mpindex", ConvertUtil.convertToString(count));
                count++;
                continue;
            }
            // 将里程碑名称为空的过滤掉
            String[] excludeMilepost = this.getExcludeMilepost();
            for (String str : excludeMilepost) {
                map.remove(str);
            }
        }
    }
    /**
     * 得到数据库字段
     *
     * @description:
     * @return
     * @author: donghang
     * @date: 2020年7月28日下午3:58:36
     * @modify:
     */
    public Map<String, Map<String, String>> getDataBaseField() {
        List<Map<String, Object>> filedMilepostList = this
                .selectExecute(SQLAdapter.getDataBaseTableFieldsSql(MpmProjectMilepostEntity.tableName));
        // 将里程碑字段中的responsiblecode修改为mileresponsiblecode
        for (Map<String, Object> filedMilepostMap : filedMilepostList) {
            if (MpmProjectMilepostEntity.FieldResponsible.toUpperCase().equals(filedMilepostMap.get("column_name"))) {
                filedMilepostMap.put("column_name", "mileresponsible");
                break;
            }
        }
        List<Map<String, Object>> filedTaskList = this
                .selectExecute(SQLAdapter.getDataBaseTableFieldsSql(MpmProjectTaskEntity.tableName));
        filedMilepostList.addAll(filedTaskList);
        // 得到数据库字段map
        Map<String, Map<String, String>> filedsInfo = new HashMap<>();
        for (Map map : filedMilepostList) {
            Map fieldInfoMap = new HashMap<>();
            String columnName = ConvertUtil.convertToString(map.get("column_name")).toLowerCase();
            String columnDateType = ConvertUtil.convertToString(map.get("data_type")).toLowerCase();
            String columnDateLength = ConvertUtil.convertToString(map.get("data_length"));
            fieldInfoMap.put("dataType", columnDateType);
            fieldInfoMap.put("dataLength", columnDateLength);
            filedsInfo.put(columnName, fieldInfoMap);
        }
        return filedsInfo;
    }
    /**
     * 数据入库
     *
     * @description:
     * @author: houyuhang
     * @date: 2023年02月15日
     * @modify:
     */
    public void executeInsertExcelData(List<Map<String, String>> listDataMap) {
        if (CollectionUtil.isEmpty(listDataMap)) {
            return;
        }
        StringBufferProxy sql = new StringBufferProxy();
        // 判断为策划变更全删全增
        if (mpmProjectPlanService.getProjectPlanChange(listDataMap.get(0).get("planid"))) {
            sql.appendSingle(" projectcode = '{0}' and planid = '{1}' ", listDataMap.get(0).get("projectcode"), listDataMap.get(0).get("planid"));
        } else {
            // 首次策划删除与导入里程碑同名的里程碑，并包括涉及的任务(删除里程碑时在deletebefore执行关联任务的删除)
            String milepostNameStr = listDataMap.stream().filter(item -> !StringUtil.isEmpty(item.get("milepostname"))).map(item -> item.get("milepostname")).collect(Collectors.joining("','", "'", "'"));
            sql.appendSingle(" projectcode = '{0}' and planid = '{1}' and milepostname in ({2}) ", listDataMap.get(0).get("projectcode"), listDataMap.get(0).get("planid"), milepostNameStr);
        }
        List<MpmProjectMilepostEntity> delMilepostEntities = this.queryByWhere(sql.toString());
        for (MpmProjectMilepostEntity delMilepostEntity : delMilepostEntities) {
            sql.clear();
            sql.appendSingle(" id in ({0}) ", delMilepostEntity.getId());
            this.deleteByWhere(sql.toString());
        }
        // 获取项目名称、mpmprojectsale表内容
        sql.clear();
        sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", listDataMap.get(0).get("projectcode"));
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
        if (ObjectUtil.isEmpty(mpmProjectEntity)) {
            throw new ServiceException("销售项目不存在，请联系管理员！");
        }
        MpmProjectSaleEntity mpmProjectSaleEntity = mpmProjectSaleService.queryById(ConvertUtil.convertToString(mpmProjectEntity.getId()));
        // 获取特殊任务
        List<Map<String, Object>> projectDmdList = datacodeCache.getCodeListMap("MpmPlanDmdTask", "", "sortcode");
        Map<String, String> dmdMap = projectDmdList.stream().collect(Collectors.toMap(item -> ConvertUtil.convertToString(item.get("name")), item -> ConvertUtil.convertToString(item.get("code")), (v1, v2) -> v1));
        // 将数据按照里程碑进行group by分类
        Map<String, List<Map<String, String>>> listDataGroup = listDataMap.stream().collect(Collectors.groupingBy(item -> item.get("mpindex")));
        for (String key : listDataGroup.keySet()) {
            List<Map<String, String>> tempData = listDataGroup.get(key);
            if (CollectionUtil.isEmpty(tempData)) {
                continue;
            }
            // 导入里程碑字段
            Map milepostMap = new HashMap<>(tempData.get(0));
            milepostMap.put("responsible", milepostMap.get("mileresponsible"));
            milepostMap.put("responsiblecode", milepostMap.get("mileresponsiblecode"));
            milepostMap.put("newadd", "1");
            milepostMap.put("sortcode", ConvertUtil.convertToInt(milepostMap.get("mpindex")));
            MpmProjectMilepostEntity mpmProjectMilepostEntity = new MpmProjectMilepostEntity();
            mpmProjectMilepostEntity.convertFromMap(milepostMap);
            mpmProjectMilepostEntity = this.insert(mpmProjectMilepostEntity);
            // 导入任务字段
            List<BasicEntity> basicEntities = new ArrayList<>();
            for (Map taskMap : tempData) {
                // 拼接里程碑code和名称
                taskMap.put("milepostcode", ConvertUtil.convertToString(mpmProjectMilepostEntity.getOperatecode()));
                taskMap.put("milepostname", ConvertUtil.convertToString(mpmProjectMilepostEntity.getMilepostname()));
                // 拼接任务默认字段
                this.concatTaskDefaultInfo(taskMap, dmdMap, mpmProjectEntity, mpmProjectSaleEntity);
                MpmProjectTaskEntity mpmProjectTaskEntity = new MpmProjectTaskEntity();
                mpmProjectTaskEntity.convertFromMap(taskMap);
                basicEntities.add(mpmProjectTaskEntity);
            }
            mpmProjectTaskService.insertBatch(basicEntities);
        }
    }
    /**
     * @Author houyuhang
     * @Description 校验里程碑任务相关发信息，处理里程碑默认字段
     * @Date 2023/02/15
     **/
    public void dealCode(List<Map<String, String>> listDataMap, int importStartRow, StringBufferProxy throwStringMessage) {
        if (CollectionUtil.isEmpty(listDataMap)) {
            return;
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled = 1 and projectcode = '{0}' and stakeholdercategory = '1' ", listDataMap.get(0).get("projectcode"));
        List<MpmProjectStakeholderEntity> mpmProjectStakeholderEntities = mpmProjectStakeholderService.queryByWhere(sql.toString());
        Map<String, String> stakeMap = mpmProjectStakeholderEntities.stream().collect(Collectors.toMap(MpmProjectStakeholderEntity::getUsername, MpmProjectStakeholderEntity::getUsercode, (v1, v2) -> (v1)));
        // 获取项目信息
        sql.clear();
        sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", listDataMap.get(0).get("projectcode"));
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
        Date mpmPlanStartDate = mpmProjectEntity.getPlanstartdate();
        Date mpmPlanEndDate = mpmProjectEntity.getPlanenddate();
        // 判断任务支持程度，是否需要系统部支持填写内容是否正确
        List<Map<String, Object>> cboYesNoList = datacodeCache.getCodeListMap("CboYesNo", "", "sortcode");
        List<Map<String, Object>> mpmCustomerApprovalList = datacodeCache.getCodeListMap("MpmCustomerApproval", "", "sortcode");
        String cboYesNoStr = cboYesNoList.stream().map(item -> ConvertUtil.convertToString(item.get("name"))).collect(Collectors.joining(","));
        String mpmCustomerApprovalStr = mpmCustomerApprovalList.stream().map(item -> ConvertUtil.convertToString(item.get("name"))).collect(Collectors.joining(","));
        List<Map<String, Object>> ruleTaskList = datacodeCache.getCodeListMap("MpmRuleInfoTask", "", "sortcode");
        for (int i = 0; i < listDataMap.size(); i++) {
            String info = "第" + (i + importStartRow) + "行";
            StringBufferProxy message = new StringBufferProxy();
            Map<String, String> listMap = listDataMap.get(i);
            // 获取里程碑、任务人员对应的code并校验是否为相关方
            String milecode = stakeMap.get(listMap.get("mileresponsible"));
            String taskcode = stakeMap.get(listMap.get("responsible"));
            if (listMap.containsKey("mpindex") && StringUtil.isEmpty(milecode)) {
                message.appendSingle("里程碑责任人不属于相关方、");
            }
            if (StringUtil.isEmpty(taskcode)) {
                message.appendSingle("任务责任人不属于相关方、");
            }
            listMap.put("mileresponsiblecode", milecode);
            listMap.put("responsiblecode", taskcode);
            // 任务开始时间不能超过任务结束时间，任务开始时间不能早于项目开始时间
            if (ConvertUtil.convertToDate(listMap.get("planstartdate")).compareTo(ConvertUtil.convertToDate(listMap.get("planenddate"))) > 0) {
                message.appendSingle("任务开始时间不能晚于任务完成时间、");
            }
            if (ConvertUtil.convertToDate(listMap.get("planstartdate")).compareTo(mpmPlanStartDate) < 0) {
                message.appendSingle("任务开始时间不能早于项目计划开始时间、");
            }
            // 判断任务支持程度，是否需要系统部支持填写内容是否正确
            if (!StringUtil.isEmpty(listMap.get("customerapproval"))) {
                listMap.put("customerapproval", datacodeCache.getValueDynamic("MpmCustomerApproval", listMap.get("customerapproval"), "name", "code"));
                if (StringUtil.isEmpty(listMap.get("customerapproval"))) {
                    message.appendSingle("任务支持程度请填写内容：" + mpmCustomerApprovalStr.replaceAll(",", "/") + "、");
                }
            }
            if (!StringUtil.isEmpty(listMap.get("needsupport"))) {
                listMap.put("needsupport", datacodeCache.getValueDynamic("CboYesNo", listMap.get("needsupport"), "name", "code"));
                if (StringUtil.isEmpty(listMap.get("needsupport"))) {
                    message.appendSingle("是否需要系统部支持请填写内容：" + cboYesNoStr.replaceAll(",", "/") + "、");
                }
            }
            // 判断加入DMD任务必填客户决策链分析
            for (Map<String, Object> ruleTask : ruleTaskList) {
                if (ConvertUtil.convertToString(ruleTask.get("name")).equals(listMap.get("taskname"))) {
                    if (StringUtil.isEmpty(listMap.get("post")) || StringUtil.isEmpty(listMap.get("customerapproval")) || StringUtil.isEmpty(listMap.get("customerattach")) || StringUtil.isEmpty(listMap.get("improveplan")) || StringUtil.isEmpty(listMap.get("needsupport"))) {
                        message.appendSingle("客户决策链分析信息必填、");
                    }
                }
            }
            // 判断关键决策链分析如果填写了其中一个，是否五个都填写了
            if ((!StringUtil.isEmpty(listMap.get("post")) || !StringUtil.isEmpty(listMap.get("customerapproval")) || !StringUtil.isEmpty(listMap.get("customerattach")) || !StringUtil.isEmpty(listMap.get("improveplan")) || !StringUtil.isEmpty(listMap.get("needsupport"))) && (StringUtil.isEmpty(listMap.get("post")) || StringUtil.isEmpty(listMap.get("customerapproval")) || StringUtil.isEmpty(listMap.get("customerattach")) || StringUtil.isEmpty(listMap.get("improveplan")) || StringUtil.isEmpty(listMap.get("needsupport")))) {
                message.appendSingle("客户决策链分析信息需填写完整、");
            }
            if(!StringUtil.isEmpty(message.toString())) {
                throwStringMessage.appendSingle(info);
                throwStringMessage.appendSingle(message.toString().substring(0, message.length()-1) + "；");
            }
        }
        // 为同一里程碑的任务赋值编号
        for (int i = 1; i < listDataMap.size(); i++) {
            Map<String, String> map = listDataMap.get(i);
            if (!map.containsKey("mpindex")) {
                Map<String, String> beforeMap = listDataMap.get(i-1);
                map.put("mpindex", beforeMap.get("mpindex"));
            }
        }
        // 校验里程碑的计划完成时间不能早于任务的计划完成时间,不能晚于项目计划结束时间，不能早于项目计划开始时间
        Map<String, List<Map<String, String>>> listDataGroup = listDataMap.stream().collect(Collectors.groupingBy(item -> item.get("mpindex")));
        for (String key : listDataGroup.keySet()) {
            StringBufferProxy milepostMessage = new StringBufferProxy();
            List<Map<String, String>> tempData = listDataGroup.get(key);
            if (CollectionUtil.isEmpty(tempData)) {
                continue;
            }
            Date tempMilepostDate = ConvertUtil.convertToDate(tempData.get(0).get("planfinishtime"));
            if (tempMilepostDate.compareTo(mpmPlanStartDate) < 0) {
                milepostMessage.appendSingle("计划完成时间不能早于项目计划开始时间、");
            }
            if (tempMilepostDate.compareTo(mpmPlanEndDate) > 0) {
                milepostMessage.appendSingle("计划完成时间不能晚于项目计划完成时间、");
            }
            for (Map<String, String> temptask : tempData) {
                Date tempTaskDate = ConvertUtil.convertToDate(temptask.get("planenddate"));
                if (tempMilepostDate.compareTo(tempTaskDate) < 0) {
                    milepostMessage.appendSingle("计划完成时间不能早于任务计划完成时间、");
                    break;
                }
            }
            if (!StringUtil.isEmpty(milepostMessage.toString())) {
                throwStringMessage.appendSingle("里程碑" + key);
                throwStringMessage.appendSingle(milepostMessage.toString().substring(0, milepostMessage.length() - 1) + "；");
            }
        }
    }
    /**
     * @description: // 与数据库校验，校验长度、数据库类型是否合法,里程碑只校验mpindex有值的内容
     * @param: [listDataMap, importStartRow]
     * @return:
     * @author: houyuhang
     * @date: 2023/02/15
     * @modify:
     */
    public void checkDataBaseFieldValid(List<Map<String, String>> listDataMap, int importStartRow, StringBufferProxy throwStringMessage) {
        // 得到数据库字段map
        Map<String, Map<String, String>> filedsInfo = this.getDataBaseField();
        // 里程碑
        // 判断excel数据是否合法，通过长度、类型判断
        for (int i = 0; i < listDataMap.size(); i++) {
            Map<String, String> map = listDataMap.get(i);
            StringBufferProxy message = new StringBufferProxy();
            String info = "第" + (i + importStartRow) + "行记录：";
            Map<String, Map<String, String>> newFiledsInfo = this.delMilepostCheck(filedsInfo, map);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String mapValue = ConvertUtil.convertToString(entry.getValue());
                String mapKey = entry.getKey().toLowerCase();
                if (newFiledsInfo.containsKey(mapKey)) {
                    Map fieldMap = newFiledsInfo.get(mapKey);
                    int maxLength = ConvertUtil.convertToInt(fieldMap.get("dataLength"));
                    String dataType = ConvertUtil.convertToString(fieldMap.get("dataType"));
                    if (fieldConvertType(mapKey,
                            SQLAdapter.toFieldDataType(dataType)) == BasicSystemConst.BasicDbFieldTypeEnum.CharType) {// 字符类型
                        if (mapValue.length() > maxLength) {
                            message.appendSingle("【" + mapValue + "】" + "超长了，最大长度为" + maxLength + "；");
                            // throw new ServiceException(info + "【" + mapValue + "】" + "超长了，最大长度为" + maxLength);
                        }
                    }
                    if (fieldConvertType(mapKey,
                            SQLAdapter.toFieldDataType(dataType)) == BasicSystemConst.BasicDbFieldTypeEnum.IntType) {// 数值类型
                        // 正负数值类型均可导入
                        Pattern pattern = Pattern.compile("^-?[0-9]\\d*(\\.\\d+)?$");
                        // 此处单独处理数字类型，控制不再判断
                        if (!ObjectUtil.isEmpty(mapValue) && !pattern.matcher(mapValue).matches()) {
                            message.appendSingle("【" + mapValue + "】" + "是非数值类型；");
                            // throw new ServiceException(info + "【" + mapValue + "】" + "是非数值类型，请修改");
                        }
                    }
                    if (fieldConvertType(mapKey,
                            SQLAdapter.toFieldDataType(dataType)) == BasicSystemConst.BasicDbFieldTypeEnum.DateType && !StringUtil.isEmpty(mapValue)) {// 日期类型
                        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                        try {
                            format.setLenient(false);
                            format.parse(mapValue);
                        } catch (ParseException e) {
                            message.appendSingle("【" + mapValue + "】" + "是非日期类型格式；");
                            // throw new ServiceException(info + "【" + mapValue + "】" + "非日期类型格式，请修改");
                        }
                    }
                }
            }
            if(!StringUtil.isEmpty(message.toString())){
                throwStringMessage.appendSingle(info);
                throwStringMessage.appendSingle(message.toString());
            }
        }
    }
    /**
     * @description: // 删除里程碑检测
     * @return:
     * @author: houyuhang
     * @date: 2023/02/15
     * @modify:
     */
    public Map<String, Map<String, String>> delMilepostCheck(Map<String, Map<String, String>> filedsInfo, Map<String, String> map) {
        Map<String, Map<String, String>> newFiledsInfo = new HashMap<>(filedsInfo);
        if (!map.containsKey("mpindex")) {
            // 将里程碑名称为空的过滤掉
            String[] excludeMilepost = this.getExcludeMilepost();
            for (String str : excludeMilepost) {
                newFiledsInfo.remove(str);
            }
        }
        return newFiledsInfo;
    }
    /**
     * @Author wangjielei
     * @Description 必填项校验
     * @Date 2022/12/2 11:13
     * @Param [listDataMap, requiredFields, fieldDescMap, importStartRow]
     * @return void
     **/
    public void checkDataRequired(List<Map<String, String>> listDataMap, String requiredFields,
                                  Map<String, String> fieldDescMap, int importStartRow, StringBufferProxy throwStringMessage) {
        if (listDataMap == null || listDataMap.size() == 0 || StringUtil.isEmpty(requiredFields)) {
            return;
        }
        String[] requiredFieldsArray = requiredFields.split(",");
        // 校验是否必填
        for (int i = 0; i < listDataMap.size(); i++) {
            Map<String, String> map = listDataMap.get(i);
            StringBufferProxy message = new StringBufferProxy();
            String info = "第" + (i + importStartRow) + "行记录：";
            String[] newRequiredFieldsArray = this.delRequireMilepostCheck(requiredFieldsArray, map);
            for (String fieldCode : newRequiredFieldsArray) {
                if (StringUtil.isEmpty(map.get(fieldCode))) {
                    message.appendSingle(fieldDescMap.get(fieldCode));
                    message.appendSingle("、");
                    // throw new ServiceException(info + fieldDescMap.get(fieldCode) + "必填");
                }
            }
            if(!StringUtil.isEmpty(message.toString())){
                throwStringMessage.appendSingle(info);
                throwStringMessage.appendSingle(message.toString().substring(0, message.length()-1));
                // 此处记录报错是编码映射不对报错或必填项没填报错
                throwStringMessage.appendSingle("必填；");
            }
        }
    }
    /**
     * @Author houyuhang
     * @Description 删除需要必填校验的里程碑
     * @Date 2023/02/15
     * @return void
     **/
    public String[] delRequireMilepostCheck(String[] requiredFieldsArray, Map<String, String> map) {
        List<String> tempList = new ArrayList<>(Arrays.asList(requiredFieldsArray));
        if (!map.containsKey("mpindex")) {
            // 将里程碑名称为空的过滤掉
            String[] excludeMilepost = this.getExcludeMilepost();
            for (String str : excludeMilepost) {
                tempList.remove(str);
            }
        }
        return tempList.toArray(new String[tempList.size()]);
    }
    /**
     * @Author houyuhang
     * @Description 获取不包含的里程碑
     * @Date 2023/02/15
     * @return void
     **/
    public String[] getExcludeMilepost() {
        String excludeMilepost = ParameterCache.getValue("excludeMilepostExcel");
        if (StringUtil.isEmpty(excludeMilepost)) {
            throw new ServiceException("导入里程碑编码未配置，请联系管理员！");
        }
        return excludeMilepost.split(",");
    }
    /**
     * @Author houyuhang
     * @Description 获取拼接的任务
     * @Date 2023/02/17
     * @return void
     **/
    public void concatTaskDefaultInfo(Map<String, Object> taskMap, Map<String, String> dmdMap, MpmProjectEntity mpmProjectEntity, MpmProjectSaleEntity mpmProjectSaleEntity) {
        String projectname = mpmProjectEntity.getProjectname();
        String deptcommoncode = mpmProjectEntity.getDeptcommoncode();
        String purchasepattern = mpmProjectSaleEntity.getPurchasepattern();
        // 任务进度
        taskMap.put("taskschedule", "0");
        // 任务状态
        taskMap.put("taskstate", "0");
        // 用户信息
        taskMap.put("applyorgname", this.getSessionUserBean().getOrg().getName());
        taskMap.put("applyorgcode", this.getSessionUserBean().getOrg().getCode());
        taskMap.put("applydeptname", this.getSessionUserBean().getDept().getName());
        taskMap.put("applydeptcode", this.getSessionUserBean().getDept().getCode());
        taskMap.put("applyusername", this.getSessionUserBean().getUser().getName());
        taskMap.put("applyusercode", this.getSessionUserBean().getUser().getCode());
        taskMap.put("username", this.getSessionUserBean().getUser().getName());
        taskMap.put("usercode", this.getSessionUserBean().getUser().getCode());
        taskMap.put("orgcode", this.getSessionUserBean().getOrg().getCode());
        taskMap.put("deptcode", this.getSessionUserBean().getDept().getCode());
        // 项目名称
        taskMap.put("projectname", mpmProjectEntity.getProjectname());
        // WBS导入标记，如果为模板固定任务，值为1不允许修改任务名称
        if (("," + ParameterCache.getValue("MpmWBSTaskTemplate") + ",").contains("," + ConvertUtil.convertToString(taskMap.get("taskname")) + ",")) {
            taskMap.put("wbstemplateflag", 1);
        }
        // dmd编号
        String dmdcode = dmdMap.get(ConvertUtil.convertToString(taskMap.get("taskname")));
        if (!StringUtil.isEmpty(dmdcode)) {
            taskMap.put("dmdtask", this.dealDmdCode(dmdcode, deptcommoncode, purchasepattern));
        }
    }
    /**
     * @Author houyuhang
     * @Description dmd编号
     * @Date 2023/02/20
     * @return void
     **/
    public int dealDmdCode(String dmdcode, String deptcommoncode, String purchasepattern) {
        // 如果不是招标项目，赋值0
        int dmdcodeNum = Integer.parseInt(dmdcode);
        if (!("," + MpmSystemConst.PurchasePattern.chanpinBid + "," + MpmSystemConst.PurchasePattern.fuwuBid + "," + MpmSystemConst.PurchasePattern.dianshang + ",").contains("," + purchasepattern + ",")) {
            return MpmSystemConst.DmdTask.Notdmd;
        }
        // 获取dmdcode为2，区分国网、南网和其他，其他直接赋值
        if (dmdcodeNum == MpmSystemConst.DmdTask.IsPerformance) {
            String realdeptcommoncode = "";
            List<Map<String, Object>> deptList = datacodeCache.getCodeListMap("LtcDeptDifferenceGrid", "", "sortcode");
            for (Map<String, Object> deptMap : deptList) {
                if (("," + deptMap.get("code") + ",").contains("," + deptcommoncode + ",")) {
                    realdeptcommoncode = ConvertUtil.convertToString(deptMap.get("name"));
                    break;
                }
            }
            if ("1".equals(realdeptcommoncode)) {
                return MpmSystemConst.DmdTask.IsPerformance;
            } else if ("2".equals(realdeptcommoncode)) {
                return MpmSystemConst.DmdTask.IsNanwangPerformance;
            } else {
                return MpmSystemConst.DmdTask.Notdmd;
            }
        }
        return dmdcodeNum;
    }
    /**
     * @Author houyuhang
     * @Description 格式化各类日期(yyyy/MM/dd、yyyy-MM-dd、dd/MM/yyyy、dd-MM-yyyy)
     * @Date 2023/03/13
     * @return void
     **/
    public String formatVariousDate(String time) {
        SimpleDateFormat formatter;
        time = time.trim();
        if (time.contains("/") && time.contains(" ") && time.length() == 19) {
            formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        } else if (time.contains("/") && time.indexOf("/") == 4) {
            formatter = new SimpleDateFormat("yyyy/MM/dd");
        } else if (time.contains("/") && (time.indexOf("/") == 1 || time.indexOf("/") == 2)) {
            formatter = new SimpleDateFormat("dd/MM/yyyy");
        } else if (time.contains("-") && time.indexOf("-") == 4) {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        } else if (time.contains("-") && (time.indexOf("-") == 1 || time.indexOf("-") == 2)) {
            formatter = new SimpleDateFormat("dd-MM-yyyy");
        } else if (!time.isEmpty() && StringUtils.isNumeric(time)) {
            Calendar calendar = new GregorianCalendar(1900,0,-1);
            Date tempDate = DateUtils.addDays(calendar.getTime(), ConvertUtil.convertToInt(time));
            formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            return formatter.format(tempDate);
        } else {
            return time;
        }
        ParsePosition pos = new ParsePosition(0);
        java.util.Date ctime = formatter.parse(time, pos);
        // 将日期格式化为yyyy-MM-dd HH:mm:ss
        formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return formatter.format(ctime);
    }
}
